package pers.qianyu.module.security.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import pers.qianyu.module.core.domain.system.vo.SysUserVO;
import pers.qianyu.module.security.domain.LoginUser;
import pers.qianyu.module.security.holder.CurrentLoginUserHolder;
import pers.qianyu.module.security.model.RequestInfoModel;
import pers.qianyu.module.security.util.SecurityUtil;
import pers.qianyu.module.system.service.AuthenticateService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author mizzle rain
 * @date 2021-05-03 21:04
 */
@Component
public class SecurityInterceptor implements HandlerInterceptor {
    @Autowired
    private AuthenticateService authenticateService;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        String requestURI = req.getRequestURI();
        String method = req.getMethod();
        RequestInfoModel model = new RequestInfoModel(requestURI, method);
        if (!SecurityUtil.inACL(model)) {
            return true;
        }
        // 校验 token
        SecurityUtil.checkToken(req);
        // 获取登录信息
        LoginUser loginUser = SecurityUtil.getLoginUser(req);
        // 获取用户信息
        SysUserVO sysUserVO = authenticateService.getUserInfoByToken(loginUser.getToken());
        loginUser.setSysUserVO(sysUserVO);
        // 将登录信息存储到ThreadLocal中
        CurrentLoginUserHolder.setLoginUser(loginUser);
        // 校验资源权限
        SecurityUtil.checkContains(sysUserVO.getResources(), model);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView modelAndView) throws Exception {
        CurrentLoginUserHolder.clear();
    }
}
